﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace myBackupClient.Model
{
    public class BackupConfig
    {
        private static readonly Lazy<BackupConfig> Lazy = new Lazy<BackupConfig>(() => new BackupConfig());
        public static BackupConfig Instance => Lazy.Value;
        private BackupConfig() 
        {
            Intialize();
            FileSystemWatcher watcher = new FileSystemWatcher
            {
                Path = AppDomain.CurrentDomain.BaseDirectory,
                NotifyFilter = NotifyFilters.LastWrite,
                Filter = "Config.xml"
            };
            watcher.Changed += (sender, e) =>
            {
                Intialize();
            };
            watcher.EnableRaisingEvents = true;
        }
        private void Intialize()
        {
            string configFile = Path.Combine(Application.StartupPath, "Config.xml");
            if (File.Exists(configFile))
            {
                try
                {
                    XElement xe = XElement.Load(configFile);
                    IpPort = xe.Attribute("IpPort").Value;
                    BackupSaveRootPath = xe.Attribute("BackupSaveRootPath").Value;
                    var items = xe.Elements("Item").Where(d => d.Attribute("Name").Value == "Path").Reverse();
                    Paths.Clear();
                    foreach (var item in items)
                    {
                        
                    }
                }
                catch (Exception ex)
                { 
                }
            }
        }
        public Dictionary<string, BackupPathConfig> Paths { get; set; } = new Dictionary<string, BackupPathConfig>();
      
        public class BackupPathConfig
        {
            public string BackupPath { get; set; }
            public string Path { get; set; }
        }

        public string IpPort { get; set; }
        public string BackupSaveRootPath { get; set; }

        public void Save()
        {
            string configFile = Path.Combine(Application.StartupPath, "Config.xml");
            XElement xe = new XElement("Config");
            xe.SetAttributeValue("IpPort", IpPort);
            xe.SetAttributeValue("BackupSaveRootPath", BackupSaveRootPath);
            foreach (var item in Paths)
            {
                XElement itemXe = new XElement("Item");
                itemXe.SetAttributeValue("Name", "Path");
                itemXe.SetAttributeValue("Value", item.Value.Path);
                xe.Add(itemXe);
            }
            xe.Save(configFile);
        }
    }
}
